#include <thread>
#include <functional>
#include <stdexcept>

class ThreadWrapper {
public:
    // 构造函数自动启动线程
    explicit ThreadWrapper(std::function<void()> func) {
        try {
            thread_ = std::thread(std::move(func));
        } catch (...) {
            throw std::runtime_error("Failed to create thread");
        }
    }

    // 禁止拷贝，允许移动
    ThreadWrapper(const ThreadWrapper&) = delete;
    ThreadWrapper& operator=(const ThreadWrapper&) = delete;
    
    ThreadWrapper(ThreadWrapper&& other) noexcept : thread_(std::move(other.thread_)) {}
    ThreadWrapper& operator=(ThreadWrapper&& other) noexcept {
        if (this != &other) {
            thread_ = std::move(other.thread_);
        }
        return *this;
    }

    // 析构函数自动join（避免资源泄漏）
    ~ThreadWrapper() {
        if (thread_.joinable()) {
            thread_.join();
        }
    }

    // 显式detach接口
    void detach() {
        if (thread_.joinable()) {
            thread_.detach();
        }
    }

private:
    std::thread thread_;
};